import * as echarts from '../../components/ec-canvas/echarts';

Component({
  properties: {
    timeType: {
      type: String,
      value: 'week'
    },
    dateRange: {
      type: String,
      value: ''
    },
    chartData: {
      type: Object,
      value: {
        categories: [],
        series: []
      }
    }
  },

  data: {
    ec: {
      lazyLoad: true
    }
  },

  lifetimes: {
    attached() {
      // 组件实例被放入页面节点树后执行
      this.isInitializing = false;
    },
    ready() {
      // 组件在视图层布局完成后执行
      // 只有在有数据时才初始化，避免重复初始化
      if (this.properties.chartData && 
          this.properties.chartData.categories && 
          this.properties.chartData.categories.length > 0) {
        this.initChart();
      }
    }
  },
  
  observers: {
    'chartData': function(chartData) {
      // 当 chartData 发生变化时，更新图表（使用非深度监听减少触发频率）
      // 避免无数据时初始化
      if (!chartData || !chartData.categories || chartData.categories.length === 0) {
        return;
      }
      
      if (this.chart) {
        // 图表已存在，直接更新
        this.updateChartOption();
      } else if (!this.isInitializing) {
        // 图表不存在且未在初始化中，延迟初始化（只初始化一次）
        this.isInitializing = true;
        setTimeout(() => {
          if (!this.chart) {
            this.initChart();
          }
          this.isInitializing = false;
        }, 300);
      }
    }
  },

  methods: {
    // 阻止事件冒泡的空方法
    stopPropagation(e) {
      // 什么都不做，只是阻止事件冒泡
    },

    onTimeTypeChange(e) {
      const type = e.currentTarget.dataset.type;
      this.triggerEvent('timechange', { type });
    },

    onPrevDate(e) {
      this.triggerEvent('prevdate');
    },

    onNextDate(e) {
      this.triggerEvent('nextdate');
    },

    // 点击图表跳转到血压记录页面
    onChartClick() {
      wx.navigateTo({
        url: '/pages/home/PressureRecord/index'
      });
    },

    // 初始化图表
    initChart() {
      // 防止重复初始化
      if (this.chart) {
        return;
      }
      
      const ecComponent = this.selectComponent('#bpChart');
      if (!ecComponent) {
        console.error('找不到#bpChart组件！');
        return;
      }
      
      ecComponent.init((canvas, width, height, dpr) => {
        this.chart = echarts.init(canvas, null, { 
          width, 
          height, 
          devicePixelRatio: dpr
        });
        canvas.setChart(this.chart);
        this.updateChartOption();
        return this.chart;
      });
    },

    // 更新图表配置
    updateChartOption() {
      if (!this.chart) {
        return;
      }
      
      const chartData = this.properties.chartData;
      if (!chartData || !chartData.series || chartData.series.length === 0) {
        return;
      }
      
      // 动态计算Y轴范围以显示所有数据
      let minValue = 40;
      let maxValue = 150;
      
      // 根据实际数据动态调整范围
      const allValues = chartData.series[0].data.filter(v => v !== null && v !== undefined);
      if (allValues.length > 0) {
        const dataMin = Math.min(...allValues);
        const dataMax = Math.max(...allValues);
        // 给数据留一些余量，向下和向上各扩展10%
        const range = dataMax - dataMin;
        const padding = Math.max(10, range * 0.1);
        minValue = Math.max(0, Math.floor(dataMin - padding));
        maxValue = Math.ceil(dataMax + padding);
      }
      
      let option = {
        backgroundColor: '#ffffff',
        grid: { 
          left: 45, 
          right: 40, 
          top: 30, 
          bottom: 50,
          containLabel: false 
        },
        tooltip: { 
          trigger: 'axis',
          backgroundColor: 'rgba(0,0,0,0.7)',
          textStyle: { color: '#fff', fontSize: 12 },
          formatter: function(params) {
            if (params && params.length > 0) {
              return `${params[0].name}<br/>心率: ${params[0].value}`;
            }
            return '';
          }
        },
        xAxis: {
          type: 'category',
          data: chartData.categories,
          boundaryGap: false,
          axisLine: { 
            show: false 
          },
          axisTick: { 
            show: false 
          },
          axisLabel: { 
            color: '#999999',
            fontSize: 10,
            margin: 10,
            interval: chartData.categories.length > 12 ? 'auto' : 0,
            lineHeight: 14 // 设置行高以支持两行显示
          }
        },
        yAxis: {
          type: 'value',
          min: minValue,
          max: maxValue,
          splitNumber: 5, // 自动分成5段
          axisLine: { 
            show: false 
          },
          axisTick: { 
            show: false 
          },
          axisLabel: { 
            color: '#999999',
            fontSize: 11,
            margin: 10
          },
          splitLine: { 
            show: true,
            lineStyle: { 
              color: '#E8E8E8',
              type: 'dashed',
              width: 1
            } 
          }
        },
        series: chartData.series.map((s, index) => {
          // 计算有效数据点数量
          const validDataCount = s.data.filter(v => v !== null && v !== undefined).length;
          
          // 如果只有一个数据点，使用scatter类型，否则使用line
          const isOnlyOnePoint = validDataCount === 1;
          
          // 使用传入的类型，如果没有则根据数据点数量决定
          const chartType = s.type || (isOnlyOnePoint ? 'scatter' : 'line');
          const chartColor = s.color || '#FF6A6A';
          
          // 如果是散点图类型，始终显示点
          const isScatterType = chartType === 'scatter';
          const shouldShowSymbol = isScatterType || isOnlyOnePoint;
          const pointSize = isScatterType ? 8 : (isOnlyOnePoint ? 10 : 0); // 散点图用8px的点
          
          const config = {
            name: s.name,
            type: chartType,
            data: s.data,
            smooth: false,
            connectNulls: true,
            symbolSize: pointSize,
            symbol: 'circle',
            showSymbol: shouldShowSymbol,
            lineStyle: {
              color: chartColor,
              width: 2
            },
            itemStyle: { 
              color: chartColor,
              borderColor: isScatterType ? chartColor : (chartType === 'bar' ? chartColor : '#ffffff'),
              borderWidth: isScatterType ? 0 : (chartType === 'bar' ? 0 : 1),
              borderRadius: chartType === 'bar' ? [4, 4, 0, 0] : 0 // 柱状图顶部圆角
            },
            emphasis: {
              itemStyle: {
                color: chartColor,
                borderColor: isScatterType ? chartColor : '#ffffff',
                borderWidth: isScatterType ? 0 : (chartType === 'bar' ? 0 : 3),
                shadowBlur: isScatterType ? 8 : 10,
                shadowColor: `rgba(${parseInt(chartColor.slice(1,3), 16)}, ${parseInt(chartColor.slice(3,5), 16)}, ${parseInt(chartColor.slice(5,7), 16)}, 0.5)`,
                scale: isScatterType ? 1.5 : 1 // 散点图悬停时放大
              }
            }
          };
          
          // 为柱状图添加特殊配置
          if (chartType === 'bar') {
            config.barWidth = '60%'; // 柱状图宽度
            config.barMaxWidth = 30; // 最大宽度
          }
          return config;
        })
      };
      
      // 使用 notMerge: true 完全替换配置，提高性能
      this.chart.setOption(option, { notMerge: true, lazyUpdate: false });
    }
  }
});
